package com.sqx.modules.health.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sqx.modules.health.common.Constants;
import com.sqx.modules.health.common.Result;
import com.sqx.modules.health.common.RoleEnum;
import com.sqx.modules.health.dto.UserDTO;
import com.sqx.modules.health.dto.UserPasswordDTO;
import com.sqx.modules.health.entity.*;
import com.sqx.modules.health.service.*;
import com.sqx.modules.health.utils.MyBeanUtil;
//import com.sqx.modules.health.utils.TokenUtils;
import com.sqx.modules.health.vo.UserDeviceVO;
import com.sqx.modules.health.vo.UserVo;
import com.sqx.modules.sys.entity.SysRoleEntity;
import com.sqx.modules.sys.entity.SysUserEntity;
import com.sqx.modules.sys.entity.SysUserRoleEntity;
import com.sqx.modules.sys.service.SysRoleService;
import com.sqx.modules.sys.service.SysUserRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户信息	 前端控制器
 * </p>
 *
 * @author gxy
 * @since 2022-04-14
 */
@Slf4j
@Api(value = "用户信息	", tags = "用户信息", description = "")
@RestController
@RequestMapping("/health/user")
public class HealthUserController {
    @Autowired
    private IUserService userService;
    @Autowired
    private IUserAddressService userAddressService;
    @Autowired
    private INcgDeviceWatchService watchService; // 智能手表service
    @Autowired
    private IHospitalService hospitalService; // 医院service
    @Autowired
    private IAgentService agentService; // 代理商service
    @Autowired
    private IUserExpandService expandService; // 用户拓展 service
    @Autowired
    private IDepartmentService departmentService; // 科室service
    @Autowired
    private IDiseasetypeService diseasetypeService; // 疾病类型 service

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private SysRoleService sysRoleService;

    // 新增或更新
    @PostMapping("/save")
    @ApiOperation(value = "新增或更新用户信息", notes = "新增或更新用户信息")
    public Result save(@RequestBody SysUserEntity user) {
        if (user.getUserId() == null || user.getUserId() == 0) {
            // 判断数据库中是否已经存在当前openid
            SysUserEntity openUser = userService.findByOpenid(user.getOpenid());
            if (openUser != null) {
                return Result.error(Constants.CODE_500, "该用户已存在,不能重复注册");
            }
            // 新增用户默认密码为123456
            user.setPassword(user.getUserId() == null ? "123456" : user.getPassword());
        }
        // 调用方法  执行添加
        Boolean save = userService.saveOrUpdate(user);
        if (save) {
            SysUserEntity service = userService.findByOpenid(user.getOpenid());
            // 给用户一个默认的token 小程序登录使用
            //service.setToken(service.getToken() == null ? TokenUtils.genToken(service.getId().toString(), service.getPassword()) : service.getToken());
        }
        return Result.success(save);
    }

    // 新增或更新(web端)
    @PostMapping("/websave")
    @ApiOperation(value = "新增或更新用户信息	", notes = "新增或更新用户信息	")
    public Result websave(@RequestBody UserVo user) {
        Agent agent = new Agent();
        UserExpand expand = new UserExpand();
        SysUserEntity saveUser = new SysUserEntity();

        SysUserEntity aaUser = userService.findByPhone(user.getPhone());
        if (aaUser == null) {
            if (user.getId() == null || user.getId() == 0) {
                // 新增用户默认密码为123456
                user.setPassword(user.getId() == null ? "123456" : user.getPassword());

                if (ObjectUtil.equals(user.getRole(), RoleEnum.ROLE_ADMIN.name())) {
                    user.setType(2);
                } else if (ObjectUtil.notEqual(user.getRole(), RoleEnum.ROLE_ADMIN.name()) && ObjectUtil.notEqual(user.getRole(), RoleEnum.ROLE_USER.name())) {
                    user.setType(1);
                } else {
                    user.setType(0);
                }
                // 如果添加的是代理商角色  就在代理商表中同时新增一条数据
                if (RoleEnum.ROLE_AGENT.name().equals(user.getRole())) {
                    agent.setName(user.getNickName());
                    agent.setAbbreviation(user.getNickName());
                    agent.setPhone(user.getPhone());
                    agent.setAddress(user.getAddress());
                    agent.setContacts(user.getNickName());
                    agent.setFlag("agent" + UUID.randomUUID().toString().replaceAll("-", ""));
                    user.setFlag(agent.getFlag());
                    agentService.save(agent);
                } else if (RoleEnum.ROLE_H_ADMIN.name().equals(user.getRole()) || RoleEnum.ROLE_H_DOCTOR.name().equals(user.getRole()) || RoleEnum.ROLE_H_NURSE.name().equals(user.getRole())) {
                    // 选择角色为 医院管理员 || 医生 || 护士角色
                    String flag = UUID.randomUUID().toString().replace("-", "");
                    expand.setUserflag(flag);
                    expand.setExp(user.getExp()); // 标识
                    expand.setContent(user.getContent()); // 工作内容
                    expand.setDepartment(user.getDepartment()); // 所属科室
                    expand.setPosition(user.getPosition()); // 职位
                    expand.setPortrait(user.getPortrait()); // 头像
                    expand.setMsgflag(1);
                    user.setExpandflag(flag); // 设置标识符统一  实现对应
                    expandService.save(expand);
                }
            } else {
                // 如果是修改代理商角色 同步修改代理商表中的数据
                if (RoleEnum.ROLE_AGENT.name().equals(user.getRole())) {
                    agent = agentService.getAgentByFlag(user.getExpandflag());

                    agent.setName(user.getNickName());
                    agent.setAbbreviation(user.getNickName());
                    agent.setPhone(user.getPhone());
                    agent.setAddress(user.getAddress());
                    agent.setContacts(user.getNickName());
                    agentService.saveOrUpdate(agent);
                } else if (RoleEnum.ROLE_H_ADMIN.name().equals(user.getRole()) || RoleEnum.ROLE_H_DOCTOR.name().equals(user.getRole()) || RoleEnum.ROLE_H_NURSE.name().equals(user.getRole())) {
                    expand = expandService.getExpandByFlag(user.getExpandflag());
                    expand.setExp(user.getExp()); // 标识
                    expand.setContent(user.getContent()); // 工作内容
                    expand.setDepartment(user.getDepartment()); // 所属科室
                    expand.setPosition(user.getPosition()); // 职位
                    expand.setPortrait(user.getPortrait()); // 头像
                    expandService.saveOrUpdate(expand);
                }
            }

            BeanUtil.copyProperties(user, saveUser);

            saveUser.setUserType(0);
            saveUser.setUsername(saveUser.getPhone());
            String salt = RandomStringUtils.randomAlphanumeric(20);
            saveUser.setPassword(new Sha256Hash(saveUser.getPassword(), salt).toHex());
            saveUser.setSalt(salt);
            userService.saveOrUpdate(saveUser);

            List<SysRoleEntity> sysRoleList = sysRoleService.list(new QueryWrapper<SysRoleEntity>().eq("role_code", saveUser.getRole()));
            if (sysRoleList.size() > 0) {
                sysUserRoleService.saveOrUpdate(saveUser.getUserId(), new ArrayList<Long>() {
                    {
                        add(sysRoleList.get(0).getRoleId());
                    }
                });
            }
            return Result.success();
        } else {
            return Result.error(Constants.CODE_500, "该手机号已存在,请重新输入");
        }
    }

    // 根据ID删除
    @GetMapping("/del/{id}")
    @ApiOperation(value = "根据ID删除用户信息	", notes = "根据ID删除用户信息	")
    public Result delete(@PathVariable Integer id) {
        // 删除用户的时候将用户名下的地址也全部删除
        userAddressService.delAddressById(id);
        SysUserEntity user = userService.getById(id);
        if (ObjectUtil.isNotEmpty(user.getExpandflag())) {
            QueryWrapper<UserExpand> wrapper = new QueryWrapper<>();
            wrapper.eq("userflag", user.getExpandflag());
            expandService.remove(wrapper);
        }
        UpdateWrapper del = new UpdateWrapper<>();
        del.set("isdelete", 1);
        del.eq(ObjectUtil.isNotEmpty(id), "id", id);
        return Result.success(userService.update(del));
    }

    // 根据IDS删除
    @GetMapping("/del/batch")
    @ApiOperation(value = "根据IDS删除用户信息	", notes = "根据IDS删除用户信息	")
    public Result deleteBatch(@RequestParam List<Integer> ids) {
        if (ObjectUtil.isEmpty(ids)) return Result.error(Constants.CODE_600, "参数错误");
        UpdateWrapper del = new UpdateWrapper<>();
        del.set("isdelete", 1);
        del.in(ObjectUtil.isNotEmpty(ids), "user_id", ids);
        return Result.success(userService.update(del));
    }

    // 查询全部
    @RequestMapping("/health/findDetectionAll")
    @ApiOperation(value = "查询全部需要检测的患者信息", notes = "查询全部需要检测的患者信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "当前页码(默认为1)", paramType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "当前页有多少条数据 (默认为10)", paramType = "Integer"),
            @ApiImplicitParam(name = "hid", value = "患者所属的医院id(不传或者为空查全部)", paramType = "Long")
    })
    public Result findDetectionAll(@RequestParam(defaultValue = "1") Integer pageNum,
                                   @RequestParam(defaultValue = "10") Integer pageSize,
                                   @RequestParam(required = false, defaultValue = "") Long hid) {
        QueryWrapper<SysUserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", 0); // 类型为患者
        queryWrapper.eq("isdetection", 1);
        if (hid != null) {
            queryWrapper.eq("hid", hid); // 患者所属医院信息
        }
        return Result.success(userService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }


    // 查询全部
    @GetMapping("/findAll")
    @ApiOperation(value = "查询全部用户信息", notes = "查询全部用户信息")
    public Result findAll() {
        List<SysUserEntity> list = userService.list();
        list.forEach(user -> user.setUsername(ObjectUtil.isEmpty(user.getNickName()) ? user.getUsername() : user.getNickName()));
        return Result.success(list);
    }

    @GetMapping("/findAllPatient")
    @ApiOperation(value = "查询全部患者信息", notes = "查询全部患者信息")
    public Result findAllPatient(@RequestParam("hid") String hid) {
        QueryWrapper<SysUserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", 0);
        if (!"null".equals(hid)) {
            queryWrapper.eq("hid", hid);
        }
        List<SysUserEntity> list = userService.list(queryWrapper);
        list.forEach(user -> user.setUsername(ObjectUtil.isEmpty(user.getNickName()) ? user.getUsername() : user.getNickName()));
        return Result.success(list);
    }

    @GetMapping("/findAllDoctor")
    @ApiOperation(value = "查询全部患者信息", notes = "查询全部患者信息")
    public Result findAllDoctor(@RequestParam("hid") String hid) {
        QueryWrapper<SysUserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("type", 0);
        if (!"null".equals(hid)) {
            queryWrapper.eq("hid", hid);
        }
//        queryWrapper.eq("role", RoleEnum.ROLE_H_ADMIN.name());// 医院管理员角色
        List<SysUserEntity> list = userService.list(queryWrapper);
        list.forEach(user -> user.setUsername(ObjectUtil.isEmpty(user.getNickName()) ? user.getUsername() : user.getNickName()));
        return Result.success(list);
    }

    @GetMapping("/findAllOperation")
    @ApiOperation(value = "查询自己手下全部运营商信息", notes = "查询自己手下全部运营商信息")
    public Result findAllOperation(@RequestParam("uid") String uid) {
        SysUserEntity user = userService.getById(uid);
        if (RoleEnum.ROLE_ADMIN.name().equals(user.getRole())) {
            return Result.success(agentService.list());
        } else {
            Agent agent = agentService.getAgentByFlag(user.getFlag());
            return Result.success(userService.findAllOperation(uid, agent.getId()));
        }
    }


    // 根据ID查询一条记录
    @GetMapping("/findOne")
    @ApiOperation(value = "根据ID查询一条记录用户信息(查看详细信息)", notes = "根据ID查询一条记录用户信息(查看详细信息)")
    public Result findOne(@RequestParam Integer id) {
        SysUserEntity user = userService.getById(id); // 首先获取用户表所有信息
        // 根据角色进行判断  是否需要从拓展表获取数据
        if (user.getType() == 0 || StringUtils.isBlank(user.getRole())) {
            // 普通用户角色  直接返回
            return Result.success(user);
        }
        // 医院相关角色  去拓展表获取数据 并进行拼接
        UserExpand expandByFlag = expandService.getExpandByFlag(user.getExpandflag());
        UserVo result = new UserVo();
        BeanUtil.copyProperties(user, result);
        if (ObjectUtil.isNotEmpty(user.getHid())) {
            Hospital hospital = hospitalService.getById(user.getHid());
            result.setHname(hospital.getName());
        }
        result.setDepartment(expandByFlag.getDepartment());
        Department department = departmentService.getById(expandByFlag.getDepartment());
        if (ObjectUtil.isNotEmpty(department)) {
            result.setDepartmentName(department.getName());
        }
        if (ObjectUtil.isNotEmpty(expandByFlag.getContent())) {
            result.setContent(expandByFlag.getContent());
        }
        if (ObjectUtil.isNotEmpty(expandByFlag.getExp())) {
            result.setExp(expandByFlag.getExp());
        }
        if (ObjectUtil.isNotEmpty(expandByFlag.getPosition())) {
            result.setPosition(expandByFlag.getPosition());
        }
        if (ObjectUtil.isNotEmpty(expandByFlag.getPortrait())) {
            result.setPortrait(expandByFlag.getPortrait());
        }
        return Result.success(result);
    }

    // 分页查询
    @GetMapping("/findPage")
    @ApiOperation(value = "分页查询用户信息	", notes = "分页查询用户信息	")
    public Result findPage(@RequestParam Integer pageNum, @RequestParam Integer pageSize,
                           @RequestParam(defaultValue = "") String hid,
                           @RequestParam(defaultValue = "") String username,
                           @RequestParam(defaultValue = "") String phone,
                           @RequestParam(defaultValue = "") String nickname) {

        QueryWrapper<SysUserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StrUtil.isNotBlank(hid), "hid", hid);
        queryWrapper.like(StrUtil.isNotBlank(username), "username", username);
        queryWrapper.like(StrUtil.isNotBlank(phone), "phone", phone);
        queryWrapper.like(StrUtil.isNotBlank(nickname), "nickname", nickname);
        queryWrapper.orderByDesc("id");
        queryWrapper.ne("type", 0);
        Page<SysUserEntity> page = userService.page(new Page<>(pageNum, pageSize), queryWrapper);
        return Result.success(getResult(page));
    }


    // 分页查询患者
    @GetMapping("/patientFindPage")
    @ApiOperation(value = "分页查询患者信息	", notes = "分页查询患者信息	")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页数", paramType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "一页数据条数", paramType = "String"),
            @ApiImplicitParam(name = "hid", value = "医院id", paramType = "Long"),
            @ApiImplicitParam(name = "username", value = "用户姓名", paramType = "String"),
            @ApiImplicitParam(name = "phone", value = "用户手机号", paramType = "String"),
            @ApiImplicitParam(name = "nickname", value = "用户昵称", paramType = "String"),
            @ApiImplicitParam(name = "uid", value = "当前登录医生的id", paramType = "Long"),
            @ApiImplicitParam(name = "role", value = "当前登录医生的权限", paramType = "String"),
    })
    public Result patientFindPage(@RequestParam Integer pageNum, @RequestParam Integer pageSize,
                                  @RequestParam(defaultValue = "") String hid,
                                  @RequestParam(defaultValue = "") String username,
                                  @RequestParam(defaultValue = "") String phone,
                                  @RequestParam(defaultValue = "") String nickname,
                                  @RequestParam(required = false, defaultValue = "") Long uid,
                                  @RequestParam(defaultValue = "") String role) {

        if (role.equals("ROLE_H_D_ADMIN")) {
            //设备科管理员
            QueryWrapper<SysUserEntity> queryWrapper = new QueryWrapper<SysUserEntity>()
                    .like(StrUtil.isNotEmpty(username), "username", username)
                    .like(StrUtil.isNotEmpty(phone), "phone", phone)
                    .like(StrUtil.isNotEmpty(nickname), "nickname", nickname)
                    .eq("type", 0)
                    .eq("isdelete", 0)
                    .eq(StrUtil.isNotEmpty(hid), "hid", hid)
                    .ne("isinner", 1)
                    .orderByAsc("user_id");
            Page<SysUserEntity> result = userService.page(new Page<>(pageNum, pageSize), queryWrapper);
            result.getRecords().forEach(item -> {
                if (ObjectUtil.isNotEmpty(item.getBelongsDoctor())) {
                    SysUserEntity user = userService.getRedisByUid(item.getBelongsDoctor());
                    if (ObjectUtil.isNotEmpty(user)) item.setDoctorName(user.getNickName());
                }
                if (ObjectUtil.isNotEmpty(item.getDiseaseType())) {
                    Diseasetype diseasetype = diseasetypeService.getById(item.getDiseaseType());
                    if (ObjectUtil.isNotEmpty(diseasetype)) item.setDiseaseName(diseasetype.getType());
                }
            });
            return Result.success(result);

        } else if (role.equals("ROLE_ADMIN")) {
            //设备科管理员
            QueryWrapper<SysUserEntity> queryWrapper = new QueryWrapper<SysUserEntity>()
                    .like(StrUtil.isNotEmpty(username), "username", username)
                    .like(StrUtil.isNotEmpty(phone), "phone", phone)
                    .like(StrUtil.isNotEmpty(nickname), "nickname", nickname)
                    .eq("type", 0)
                    .eq("isdelete", 0)
                    .orderByAsc("user_id");
            Page<SysUserEntity> result = userService.page(new Page<>(pageNum, pageSize), queryWrapper);
            result.getRecords().forEach(item -> {
                if (ObjectUtil.isNotEmpty(item.getBelongsDoctor())) {
                    SysUserEntity user = userService.getRedisByUid(item.getBelongsDoctor());
                    if (ObjectUtil.isNotEmpty(user)) item.setDoctorName(user.getNickName());
                }
                if (ObjectUtil.isNotEmpty(item.getDiseaseType())) {
                    Diseasetype diseasetype = diseasetypeService.getById(item.getDiseaseType());
                    if (ObjectUtil.isNotEmpty(diseasetype)) item.setDiseaseName(diseasetype.getType());
                }
            });
            return Result.success(result);

        } else {

            QueryWrapper<SysUserEntity> queryWrapper = new QueryWrapper<SysUserEntity>()
                    .like(StrUtil.isNotEmpty(username), "username", username)
                    .like(StrUtil.isNotEmpty(phone), "phone", phone)
                    .like(StrUtil.isNotEmpty(nickname), "nickname", nickname)
                    .eq("type", 0)
                    .eq("isdelete", 0)
                    .eq(StrUtil.isNotEmpty(hid), "hid", hid)
                    .eq("belongs_doctor", uid)
                    .ne("isinner", 1)
                    .orderByAsc("user_id");
            Page<SysUserEntity> result = userService.page(new Page<>(pageNum, pageSize), queryWrapper);
            result.getRecords().forEach(item -> {
                if (ObjectUtil.isNotEmpty(item.getBelongsDoctor())) {
                    SysUserEntity user = userService.getRedisByUid(item.getBelongsDoctor());
                    if (ObjectUtil.isNotEmpty(user)) item.setDoctorName(user.getNickName());
                }
                if (ObjectUtil.isNotEmpty(item.getDiseaseType())) {
                    Diseasetype diseasetype = diseasetypeService.getById(item.getDiseaseType());
                    if (ObjectUtil.isNotEmpty(diseasetype)) item.setDiseaseName(diseasetype.getType());
                }
            });
            return Result.success(result);

        }
    }


    @GetMapping("/doctorFindPage")
    @ApiOperation(value = "分页查询所有医生信息", notes = "分页查询所有医生信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页数", paramType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "一页数据条数", paramType = "String"),
            @ApiImplicitParam(name = "hid", value = "医院id", paramType = "Long"),
            @ApiImplicitParam(name = "role", value = "查询角色： 1 护士 2 其他", paramType = "String"),
            @ApiImplicitParam(name = "flag", value = "小程序请求标识", paramType = "Integer"),
    })
    public Result doctorFindPage(@RequestParam Integer pageNum, @RequestParam Integer pageSize,
                                 @RequestParam(required = false, defaultValue = "") Long hid,
                                 @RequestParam(required = false, defaultValue = "") String role,
                                 @RequestParam(required = false, defaultValue = "") String name,
                                 @RequestParam(required = false, defaultValue = "") Long flag) {

        QueryWrapper<SysUserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", 1);
        queryWrapper.eq("isdelete", 0);
        if (StringUtils.isNotBlank(role)) {
            if ("1".equals(role)) {
                queryWrapper.eq("role", RoleEnum.ROLE_H_NURSE.name());
            } else {
                queryWrapper.eq("role", RoleEnum.ROLE_H_DOCTOR.name());
            }
        } else {
            queryWrapper.like("role", "ROLE_H");
        }
        if (hid != null) {
            queryWrapper.eq("hid", hid);
        }
        queryWrapper.like(StringUtils.isNotBlank(name), "username", name);
        queryWrapper.orderByAsc("user_id");
        Page<SysUserEntity> page = userService.page(new Page<>(pageNum, pageSize), queryWrapper);
        List<UserVo> userVos = MyBeanUtil.collectionCopy(page.getRecords(), UserVo.class);
        for (UserVo userVo : userVos) {
            if (StringUtils.isNotBlank(userVo.getExpandflag())) {
                UserExpand expandByFlag = expandService.getExpandByFlag(userVo.getExpandflag());
                if (ObjectUtil.isNotEmpty(expandByFlag)) {
                    userVo.setMsgflag(expandByFlag.getMsgflag());
                    if (expandByFlag.getMsgflag() == 0) {
                        continue;
                    }
                    userVo.setDepartment(expandByFlag.getDepartment());
                    if (expandByFlag.getDepartment() != null) {
                        userVo.setDepartmentName(departmentService.getById(expandByFlag.getDepartment()).getName());
                    }
                    userVo.setContent(expandByFlag.getContent());
                    userVo.setExp(expandByFlag.getExp());
                    userVo.setPosition(expandByFlag.getPosition());
                    userVo.setPortrait(expandByFlag.getPortrait());
                }
            }
        }
        Page<UserVo> result = new Page<>();
        result.setTotal(page.getTotal());
        if (flag != null) {
            result.setRecords(userVos.stream().filter(userVo -> userVo.getMsgflag() == 1).collect(Collectors.toList()));
        } else {
            result.setRecords(userVos);
        }
        return Result.success(result);
    }

    /**
     * 封装返回数据
     *
     * @param page
     * @return
     */
    private Page<UserVo> getResult(Page<SysUserEntity> page) {
        List<UserVo> userVos = MyBeanUtil.collectionCopy(page.getRecords(), UserVo.class);
        for (UserVo userVo : userVos) {
            if (StringUtils.isNotBlank(userVo.getExpandflag())) {
                UserExpand expandByFlag = expandService.getExpandByFlag(userVo.getExpandflag());
                userVo.setDepartment(expandByFlag.getDepartment());
                if (expandByFlag.getDepartment() != null) {
                    userVo.setDepartmentName(departmentService.getById(expandByFlag.getDepartment()).getName());
                }
                userVo.setContent(expandByFlag.getContent());
                userVo.setExp(expandByFlag.getExp());
                userVo.setPosition(expandByFlag.getPosition());
                userVo.setPortrait(expandByFlag.getPortrait());
            } else {
                continue;
            }
        }
        Page<UserVo> result = new Page<>();
        result.setTotal(page.getTotal());
        result.setRecords(userVos);
        return result;
    }

    @PostMapping("/login")
    public Result login(@RequestBody UserDTO userDTO) {
        String phone = userDTO.getPhone();
        String password = userDTO.getPassword();
        System.out.println(phone);
        if (StrUtil.isBlank(phone) || StrUtil.isBlank(password)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        UserDTO dto = userService.login(userDTO);
        return Result.success(dto);
    }

    @GetMapping("/username/{username}")
    public Result findByUsername(@PathVariable String username) {
        QueryWrapper<SysUserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return Result.success(userService.getOne(queryWrapper));
    }


    @PostMapping("/register")
    public Result register(@RequestBody UserDTO userDTO) {
        String phone = userDTO.getPhone();
        String password = userDTO.getPassword();
        if (StrUtil.isBlank(phone) || StrUtil.isBlank(password)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        return Result.success(userService.register(userDTO));
    }

    @ApiOperation(value = "根据openid查询用户")
    @GetMapping("/searchUser")
    public Result searchUser(@RequestParam String openid) {
        SysUserEntity user = userService.searchUser(openid);
        if (ObjectUtil.isNotEmpty(user)) {
            // 将用户的token进行更新
            //user.setToken(TokenUtils.genToken(user.getId().toString(), user.getPassword()));
            userService.updateToken(user);
            return Result.success(user);
        } else {
            return Result.error();
        }
    }

    /**
     * 修改密码
     *
     * @param userPasswordDTO
     * @return
     */
    @PostMapping("/password")
    public Result password(@RequestBody UserPasswordDTO userPasswordDTO) {
        userService.updatePassword(userPasswordDTO);
        return Result.success();
    }

    /**
     * 用户查看自己名下的设备
     */
    @GetMapping("/getUserDevice")
    public Result getUserDevice(@RequestParam("id") Long id) {
        try {
            // 首先获取到所有的设备id
            List<UserDevice> devices = userService.getUserDevice(id);

            List<UserDeviceVO> deviceVOS = new ArrayList<>();
            // 遍历集合 查询设备信息
            for (int i = 0; i < devices.size(); i++) {
                UserDeviceVO vo = new UserDeviceVO();
                // 判断设备类型
                if (devices.get(i).getDevicetype() == 1) {
                    // 智能手表
                    NcgDeviceWatch watch = watchService.getById(devices.get(i).getDeviceid());
                    BeanUtil.copyProperties(watch, vo);
                    vo.setDevicetype(1); // 设置手表类型为智能手表
                    vo.setUid(id); // 设置用户id
                    vo.setDeviceid(devices.get(i).getDeviceid()); // 设置 设备id
                    deviceVOS.add(vo);
                }
            }

            // 根据医院id 获取医院名称
            for (UserDeviceVO deviceVO : deviceVOS) {
                if (ObjectUtil.isNotEmpty(deviceVO.getHid())) {
                    Hospital hospital = hospitalService.getById(deviceVO.getHid());
                    deviceVO.setHname(hospital.getName() == null ? hospital.getAbbreviation() : hospital.getName());
                }
            }
            return Result.success(deviceVOS);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(Constants.CODE_500, "查询失败,请重试!");
        }
    }

    @GetMapping("/UserUnBinding")
    public Result UserUnBinding(@RequestParam("uid") Long uid, @RequestParam("deviceid") Long deviceid) {

        try {
            // 删除设备表对应信息
            userService.UserUnBinding(uid, deviceid);
            // 更新设备表信息
            hospitalService.unBinding(String.valueOf(deviceid), 2);
            return Result.success("解除绑定成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(Constants.CODE_500, "解绑失败");
        }
    }

    @GetMapping("/findCheckList")
    public Result findCheckList(@RequestParam Long hid) {
        if (ObjectUtil.isEmpty(hid)) {
            return Result.error(Constants.CODE_500, "参数错误");
        }
        List<String> result = userService.getResult(hid);
        return Result.success(result);
    }

    @GetMapping("/findMe")
    public Result findMe(@RequestParam Long id) {
        if (ObjectUtil.isEmpty(id)) {
            return Result.error(Constants.CODE_500, "参数错误");
        }

        SysUserEntity user = userService.getById(id);
        UserExpand expandByFlag = expandService.getExpandByFlag(user.getExpandflag());
        return Result.success(expandByFlag.getMsgflag());
    }

    // 分页查询患者
    @GetMapping("/innerPatientFindPage")
    @ApiOperation(value = "分页查询院内患者信息	", notes = "分页查询患者信息	")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页数", paramType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "一页数据条数", paramType = "String"),
            @ApiImplicitParam(name = "hid", value = "医院id", paramType = "Long"),
            @ApiImplicitParam(name = "username", value = "用户姓名", paramType = "String"),
            @ApiImplicitParam(name = "phone", value = "用户手机号", paramType = "String"),
            @ApiImplicitParam(name = "nickname", value = "用户昵称", paramType = "String"),
            @ApiImplicitParam(name = "uid", value = "当前登录医生的id", paramType = "Long"),
            @ApiImplicitParam(name = "role", value = "当前登录医生的权限", paramType = "String"),
    })
    public Result innerPatientFindPage(@RequestParam Integer pageNum, @RequestParam Integer pageSize,
                                       @RequestParam(defaultValue = "") String hid,
                                       @RequestParam(defaultValue = "") String username,
                                       @RequestParam(defaultValue = "") String phone,
                                       @RequestParam(defaultValue = "") String nickname,
                                       @RequestParam(required = false, defaultValue = "") Long uid,
                                       @RequestParam(defaultValue = "") String role) {

        QueryWrapper<SysUserEntity> queryWrapper = new QueryWrapper<SysUserEntity>()
                .like(StrUtil.isNotEmpty(username), "username", username)
                .like(StrUtil.isNotEmpty(phone), "phone", phone)
                .like(StrUtil.isNotEmpty(nickname), "nickname", nickname)
                .eq("type", 0)
                .eq(StrUtil.isNotEmpty(hid), "hid", hid)
                .eq("isinner", 1)
                .orderByDesc("createtime")
                .orderByAsc("discharge");
        Page<SysUserEntity> result = userService.page(new Page<>(pageNum, pageSize), queryWrapper);
        //List<Diseasetype> diseasetypeList = diseasetypeService.list();
        result.getRecords().forEach(item -> {
            if (ObjectUtil.isNotEmpty(item.getBelongsDoctor())) {
                SysUserEntity user = userService.getRedisByUid(item.getBelongsDoctor());
                if (ObjectUtil.isNotEmpty(user)) {
                    item.setDoctorName(user.getNickName());
                }
            }
            /*if (ObjectUtil.isNotEmpty(item.getDiseaseType())) {
                for (Diseasetype diseasetype : diseasetypeList) {
                    if (ObjectUtil.isNotEmpty(diseasetype) && diseasetype.getId().toString().equals(item.getDiseaseType())) {
                        item.setDiseaseName(diseasetype.getType());
                    }
                }
            }*/
        });
        return Result.success(result);

    }

    @GetMapping("/userListByRole")
    @ApiOperation(value = "分页查询院内患者信息	", notes = "分页查询患者信息	")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "hid", value = "医院id", paramType = "Long"),
            @ApiImplicitParam(name = "roleName", value = "当前登录医生的权限", paramType = "String"),
    })
    public Result innerPatientFindPage(
            @RequestParam(defaultValue = "") String hid,
            @RequestParam(defaultValue = "") String roleName) {

        QueryWrapper<SysUserEntity> queryWrapper = new QueryWrapper<SysUserEntity>()
                .eq(StrUtil.isNotEmpty(hid), "hid", hid)
                .eq(StrUtil.isNotEmpty(roleName), "role", roleName)
                .orderByAsc("user_id");
        return Result.success(userService.list(queryWrapper));
    }

    // 新增或更新(web端)
    @PostMapping("/saveInnerPatient")
    @ApiOperation(value = "新增或更新用户信息	", notes = "新增或更新用户信息	")
    public Result saveInnerPatient(@RequestBody SysUserEntity user) {

        SysUserEntity saveUser = new SysUserEntity();

        SysUserEntity aaUser = userService.findByPhone(user.getPhone());
        if (aaUser == null) {
            if (user.getUserId() == null || user.getUserId() == 0) {
                // 新增用户默认密码为123456
                String name = RoleEnum.ROLE_H_DOCTOR.name();
                user.setPassword(user.getUserId() == null ? "123456" : user.getPassword());

                if (ObjectUtil.equals(user.getRole(), RoleEnum.ROLE_ADMIN.name())) {
                    user.setType(2);
                } else if (ObjectUtil.notEqual(user.getRole(), RoleEnum.ROLE_ADMIN.name()) && ObjectUtil.notEqual(user.getRole(), RoleEnum.ROLE_USER.name())) {
                    user.setType(1);
                } else {
                    user.setType(0);
                }
            }
            BeanUtil.copyProperties(user, saveUser);
            return Result.success(userService.saveOrUpdate(saveUser));
        } else {
            BeanUtil.copyProperties(user, saveUser);
            saveUser.setUserId(aaUser.getUserId());
            return Result.success(userService.saveOrUpdate(saveUser));
            //return Result.error(Constants.CODE_500, "该手机号已存在,请重新输入");
        }
    }


}

